package com.alex.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: liwenhao
 * @Date: 2022/3/26 23:19
 * @Description:
 */
@Slf4j
public class SafetyEncryptProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        environment.getPropertySources().stream()
                .filter(m -> m instanceof OriginTrackedMapPropertySource)
                .forEach(m -> {
                    OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource) m;
                    for (String propertyName : source.getPropertyNames()) {
                        if ("spring.datasource.password".equals(propertyName)) {
                            Map<String, Object> map = new HashMap<>();
                            // 做解密处理
                            String property = (String) source.getProperty(propertyName);
                            String s = DESedeUtil.decode3DES(DESedeUtil.KEY, property);
                            System.out.println("密文：" + property);
                            System.out.println("解密后的：" + s);
                            map.put(propertyName, s);

                            // 注意要添加到前面，覆盖
                            environment.getPropertySources().addFirst(new MapPropertySource(propertyName, map));
                        }
                    }
                });
    }
}
